package com.ch.gsyvideo;

import android.content.Context;
import android.content.res.AssetFileDescriptor;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.net.Uri;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.View;
import android.widget.ImageView;

import com.shuyu.gsyvideoplayer.listener.VideoAllCallBack;
import com.shuyu.gsyvideoplayer.player.IjkPlayerManager;
import com.shuyu.gsyvideoplayer.player.PlayerFactory;
import com.shuyu.gsyvideoplayer.player.SystemPlayerManager;
import com.shuyu.gsyvideoplayer.utils.GSYVideoType;

import java.io.IOException;

public class VideoManager {
    private SuperRedVideoPlayer mVideo;
    private MediaPlayer mMediaPlayer;
    private SurfaceHolder mHolder;
    private onVideoCallback onVideoCallback;
    private onVideoCallbackStart onVideoCallbackStart;
    private boolean loop;

    public boolean isFullScreen() {
        return isFullScreen;
    }

    public void setFullScreen(boolean fullScreen) {
        isFullScreen = fullScreen;
    }

    private boolean isFullScreen;
    private int playerState;//1 播放 2 暂停  3  停止

    public static VideoManager defaultInstance;

    /**
     * Convenience singleton for apps using a process-wide EventBus instance.
     */
    public static VideoManager getDefault() {
        VideoManager instance = defaultInstance;
        if (instance == null) {
            synchronized (VideoManager.class) {
                instance = VideoManager.defaultInstance;
                if (instance == null) {
                    instance = VideoManager.defaultInstance = new VideoManager();
                }
            }
        }
        return instance;
    }

    public interface onVideoCallbackStart {
        void onPlayStart();

        void onPlayStop();
    }

    public interface onVideoCallback {
        void onPlayCompletion();
    }

    public void startFullScreen(Context context){
        if(mVideo!=null){
            mVideo.startWindowFullscreen(context,false,false);
            isFullScreen=true;
        }
    }

    public void exitFullScreen(){
        if(mVideo!=null){
            mVideo.onBackFullscreen();
            isFullScreen=false;
        }
    }

    /**
     * 三方库调用，适合网络视频播放
     *
     * @param mContext
     * @param videoPlayer
     *
     * @param loop
     */
    public void startPlay(Context mContext, SuperRedVideoPlayer videoPlayer, String url, boolean loop) {
        mVideo = videoPlayer;
        PlayerFactory.setPlayManager(IjkPlayerManager.class);
        GSYVideoType.setShowType(GSYVideoType.SCREEN_MATCH_FULL);
        videoPlayer.setUp(url, true, "");
        //增加封面
        videoPlayer.setLooping(true);
        videoPlayer.setIsTouchWiget(false);
        videoPlayer.startPlayLogic();
        videoPlayer.setVideoAllCallBack(new VideoAllCallBack() {
            @Override
            public void onStartPrepared(String url, Object... objects) {

            }

            @Override
            public void onPrepared(String url, Object... objects) {

            }

            @Override
            public void onClickStartIcon(String url, Object... objects) {

            }

            @Override
            public void onClickStartError(String url, Object... objects) {

            }

            @Override
            public void onClickStop(String url, Object... objects) {

            }

            @Override
            public void onClickStopFullscreen(String url, Object... objects) {

            }

            @Override
            public void onClickResume(String url, Object... objects) {

            }

            @Override
            public void onClickResumeFullscreen(String url, Object... objects) {

            }

            @Override
            public void onClickSeekbar(String url, Object... objects) {

            }

            @Override
            public void onClickSeekbarFullscreen(String url, Object... objects) {

            }

            @Override
            public void onAutoComplete(String url, Object... objects) {
                if (loop) {
                    videoPlayer.startPlayLogic();
                }

            }

//            @Override
//            public void onComplete(String url, Object... objects) {
//
//            }

            @Override
            public void onEnterFullscreen(String url, Object... objects) {

            }

            @Override
            public void onQuitFullscreen(String url, Object... objects) {

            }

            @Override
            public void onQuitSmallWidget(String url, Object... objects) {

            }

            @Override
            public void onEnterSmallWidget(String url, Object... objects) {

            }

            @Override
            public void onTouchScreenSeekVolume(String url, Object... objects) {

            }

            @Override
            public void onTouchScreenSeekPosition(String url, Object... objects) {

            }

            @Override
            public void onTouchScreenSeekLight(String url, Object... objects) {

            }

            @Override
            public void onPlayError(String url, Object... objects) {

            }

            @Override
            public void onClickStartThumb(String url, Object... objects) {

            }

            @Override
            public void onClickBlank(String url, Object... objects) {

            }

            @Override
            public void onClickBlankFullscreen(String url, Object... objects) {

            }
        });
    }

    /**
     * 三方库调用，适合网络视频播放
     *
     * @param mContext
     * @param videoPlayer
     * @param raw
     * @param loop
     */
    public void startPlay(Context mContext, SuperRedVideoPlayer videoPlayer, int raw, boolean loop) {
        mVideo = videoPlayer;
        PlayerFactory.setPlayManager(SystemPlayerManager.class);
        GSYVideoType.setShowType(GSYVideoType.SCREEN_MATCH_FULL);
        //本地视频播放
        Uri uri = Uri.parse("android.resource://" + mContext.getPackageName() + "/" + raw);
        videoPlayer.setUp(uri.toString(), true, "");
        //增加封面
        videoPlayer.setLooping(true);
        videoPlayer.setIsTouchWiget(false);
        videoPlayer.startPlayLogic();
        videoPlayer.setVideoAllCallBack(new VideoAllCallBack() {
            @Override
            public void onStartPrepared(String url, Object... objects) {

            }

            @Override
            public void onPrepared(String url, Object... objects) {

            }

            @Override
            public void onClickStartIcon(String url, Object... objects) {

            }

            @Override
            public void onClickStartError(String url, Object... objects) {

            }

            @Override
            public void onClickStop(String url, Object... objects) {

            }

            @Override
            public void onClickStopFullscreen(String url, Object... objects) {

            }

            @Override
            public void onClickResume(String url, Object... objects) {

            }

            @Override
            public void onClickResumeFullscreen(String url, Object... objects) {

            }

            @Override
            public void onClickSeekbar(String url, Object... objects) {

            }

            @Override
            public void onClickSeekbarFullscreen(String url, Object... objects) {

            }

            @Override
            public void onAutoComplete(String url, Object... objects) {
                if (loop) {
                    videoPlayer.startPlayLogic();
                }

            }
//
//            @Override
//            public void onComplete(String url, Object... objects) {
//
//            }

            @Override
            public void onEnterFullscreen(String url, Object... objects) {

            }

            @Override
            public void onQuitFullscreen(String url, Object... objects) {

            }

            @Override
            public void onQuitSmallWidget(String url, Object... objects) {

            }

            @Override
            public void onEnterSmallWidget(String url, Object... objects) {

            }

            @Override
            public void onTouchScreenSeekVolume(String url, Object... objects) {

            }

            @Override
            public void onTouchScreenSeekPosition(String url, Object... objects) {

            }

            @Override
            public void onTouchScreenSeekLight(String url, Object... objects) {

            }

            @Override
            public void onPlayError(String url, Object... objects) {

            }

            @Override
            public void onClickStartThumb(String url, Object... objects) {

            }

            @Override
            public void onClickBlank(String url, Object... objects) {

            }

            @Override
            public void onClickBlankFullscreen(String url, Object... objects) {

            }
        });
    }

    //设备播放的播放
    public void setThumb(Context mContext, SuperRedVideoPlayer videoPlayer, int res, int imgsrc) {
        //PlayerFactory.setPlayManager(SystemPlayerManager.class);
        Uri source1 = Uri.parse("android.resource://" + mContext.getPackageName() + "/" + res);
        videoPlayer.setUp(source1.toString(), true, "");
        //增加封面
        ImageView imageView = new ImageView(mContext);
        imageView.setScaleType(ImageView.ScaleType.FIT_XY);
        imageView.setImageResource(imgsrc);
        videoPlayer.setThumbImageView(imageView);
        //增加title
        videoPlayer.getTitleTextView().setVisibility(View.VISIBLE);
        //设置返回键
        videoPlayer.getBackButton().setVisibility(View.VISIBLE);
        //是否可以滑动调整
        videoPlayer.setIsTouchWiget(true);

    }


    /**
     * 系统播放
     */
    public void startPlay(Context mContext, SurfaceView surfaceView, int src, boolean loop, onVideoCallback onCallback) {
        if (mMediaPlayer == null) mMediaPlayer = new MediaPlayer();
        if (onVideoCallback == null) this.onVideoCallback = onCallback;
        this.loop = loop;
        if (mHolder == null) {
            initSurface(surfaceView, mContext, src);
        } else {
            start(mMediaPlayer, mHolder, mContext, src);
        }
    }

    /**
     * 系统播放
     */
    public void startPlay(Context mContext, SurfaceView surfaceView, int src, boolean loop, onVideoCallback onCallback, onVideoCallbackStart onCallbackStart) {
        if (mMediaPlayer == null) mMediaPlayer = new MediaPlayer();
        if (onVideoCallback == null) this.onVideoCallback = onCallback;
        if (onVideoCallbackStart == null) this.onVideoCallbackStart = onCallbackStart;
        this.loop = loop;
        if (mHolder == null) {
            initSurface(surfaceView, mContext, src);
        } else {
            start(mMediaPlayer, mHolder, mContext, src);
        }
    }

    public void initSurface(SurfaceView surfaceView, Context mContext, int src) {
        mHolder = surfaceView.getHolder();
        mHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
        mHolder.addCallback(new SurfaceHolder.Callback() {
            @Override
            public void surfaceChanged(SurfaceHolder holder, int arg1, int arg2, int arg3) {

            }

            @Override
            public void surfaceCreated(SurfaceHolder holder) {
                try {
                    start(mMediaPlayer, mHolder, mContext, src);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void surfaceDestroyed(SurfaceHolder holder) {
                mMediaPlayer.stop();
                mMediaPlayer.release();
                mMediaPlayer = null;
                mHolder = null;
                onVideoCallback = null;
                playerState = 3;
                if (onVideoCallbackStart != null) {
                    onVideoCallbackStart.onPlayStop();
                }
            }
        });

    }


    public void onSystemVideoRestart() {
        if (mMediaPlayer != null) {
            mMediaPlayer.start();
            playerState = 1;
            if (onVideoCallbackStart != null) {
                onVideoCallbackStart.onPlayStart();
            }
        }
    }


    public void onSystemVideoPause() {
        if (mMediaPlayer != null) {
            mMediaPlayer.isPlaying();
            mMediaPlayer.pause();
            playerState = 2;

        }
    }

    public boolean isSystemVideoPlaying() {
        if (mMediaPlayer != null) {
            return mMediaPlayer.isPlaying();
        }
        return false;


    }

    public void onSystemVideoReset() {
        if (mMediaPlayer != null) {
            mMediaPlayer.isPlaying();
            mMediaPlayer.reset();
            playerState = 3;
        }
    }

    public void onSystemVideoResume() {
        if (mMediaPlayer != null) {
            mMediaPlayer.start();
        }
    }

    private void start(final MediaPlayer mMediaPlayer, SurfaceHolder mHolder, Context mContext, int src) {
        AssetFileDescriptor afd = mContext.getResources().openRawResourceFd(src);
        if (mMediaPlayer.isPlaying()) {
            mMediaPlayer.pause();
            mMediaPlayer.reset();
            playerState = 3;
            if (onVideoCallbackStart != null) {
                onVideoCallbackStart.onPlayStop();
            }
            mMediaPlayer.setDisplay(mHolder);
        }

        mMediaPlayer.setLooping(loop);
        mMediaPlayer.setOnCompletionListener(mp -> {
            onVideoCallback.onPlayCompletion();
        });
        try {
            mMediaPlayer.setDataSource(afd.getFileDescriptor(), afd.getStartOffset(), afd.getLength());
        } catch (IOException e) {
            e.printStackTrace();
        }
        mMediaPlayer.setDisplay(mHolder);
        mMediaPlayer.prepareAsync();
        mMediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
        mMediaPlayer.setOnPreparedListener(mp -> {
                    playerState = 1;
                    if (onVideoCallbackStart != null) {
                        onVideoCallbackStart.onPlayStart();
                    }
                    mMediaPlayer.start();
                }
        );
    }


    public void onVideoPause() {
        if (mVideo != null) {
            mVideo.isInPlayingState();
            mVideo.onVideoPause();
        }

    }

    public void onVideoReset() {
        if (mVideo != null) {
            mVideo.isInPlayingState();
            mVideo.onVideoReset();
        }

    }

    public void onVideoResume() {
        if (mVideo != null) {
            mVideo.onVideoResume();
        }
    }

    public int getPlayerState() {
        return playerState;
    }

    public void setPlayerState(int playerState) {
        this.playerState = playerState;
    }

    public void stopPlay() {
        if(mVideo!=null){
            mVideo.onVideoReset();
        }

    }
}
